import Vue from 'vue';

import $web3js from '../web3.js';
import numberUtils from '@/utils/numberUtils';

const usdtContract = require('./usdtContract.json')

let web3 = $web3js.getWeb3();

let contractAddress = '0xa71EdC38d189767582C38A3145b5873052c3e47a';
let contractConst = {
    contract: web3 ? new web3.eth.Contract(usdtContract.abi, contractAddress) : '',
}
const getHusdAddress = () => {
    return contractAddress;
}

const getUsdtAddress = () => {
}

const getHusdContract = () => {
    return contractConst.contract;
}

const fromUsdtValue = async (value) => {
    let _decimals = await getUsdtDecimals();
    return await numberUtils.movePointLeft(value, _decimals);
}

const toUsdtValue = async (value) => {
    let _decimals = await getUsdtDecimals();
    return await numberUtils.movePointRight(value, _decimals);
}

let USDT_DECIMALS = undefined;
const getUsdtDecimals = () => {
    let _decimals = USDT_DECIMALS;
    if (!_decimals) {
        _decimals = $web3js.commonCall(getHusdContract().methods.decimals);
        if (!!_decimals) {
            USDT_DECIMALS = _decimals
        }
    }
    return _decimals;
}

const getUsdtBalance = async (address) => {
    return $web3js.commonCallAndHandler(getHusdContract().methods.balanceOf, fromUsdtValue, address);
}

const getUsdtAllowance = (owner, spender) => {
    return $web3js.commonCallAndHandler(getHusdContract().methods.allowance, fromUsdtValue, owner, spender);
}

const usdtApprove = async (address, value) => {
    value = await toUsdtValue(value)
    return $web3js.commonSend(getHusdContract().methods.approve, address, value);
}

const usdtApproveEstimateGas = async (address, value) => {
    value = await toUsdtValue(value)
    return $web3js.commonEstimateGas(getHusdContract().methods.approve, address, value);
}

const usdtTransfer = async (address, value) => {
    value = await toUsdtValue(value)
    return $web3js.commonSend(getHusdContract().methods.transfer, address, value);
}

export default {
    getUsdtAddress,
    getHusdAddress,
    getHusdContract,
    fromUsdtValue,
    toUsdtValue,
    getUsdtDecimals,
    getUsdtAllowance,
    getUsdtBalance,
    usdtApprove,
    usdtApproveEstimateGas,
    usdtTransfer
}
